<?php

namespace app\api\controller;


use app\admin\model\FeedbackCate;
use app\common\controller\Api;
use app\admin\model\Feedback as FeedbackModel;

/**
 * 问题反馈接口
 */
class Feedback extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     *  问题反馈详情
     *
     */
    public function index()
    {
        //  用户反馈分类表
        $models = new FeedbackCate();//连表
        $cate = $models::where(['status' => 1])->field('id,title')->select();//查询id，title
        foreach ($cate as $v) {
            $v['id'];//遍历id
        }
        // 添加用户反馈内容
        $model = new FeedbackModel();//连表
        $data = input();//接表单值
        $data['feedback_cate_id'] = $v['id'];//反馈分类表的id
        $data['user_id'] = $this->auth->id;//用户id
        // 上传文件
        if ($files = $_FILES) {
            $imageArr = Array();
            foreach ($files as $file) {
                $imageName = $file['name'];
                //后缀名
                $ext = strtolower(substr(strrchr($imageName, '.'), 1));
                //保存文件名
                $fileName = uniqid();
                $tmp = $file['tmp_name'];
                //保存 = 路径 + 文件名 + 后缀名
                $imageSavePath = '../public/uploads/images/' . $fileName . '.' . $ext;
                $info = move_uploaded_file($tmp, $imageSavePath);

                if ($info) {
                    $path = "/uploads/images/" . $fileName . '.' . $ext;
                    array_push($imageArr, $path);
                } else {
                    $this->error(400, '上传失败！');
                }
            }
            $data['image'] = implode(',', $imageArr);
        }

        $res = $this->validate($data, 'Feedback.add');//验证$data
        if ($res !== true) $this->error($res, [], 500);//判断
        if ($model->save($data)) {//自动验证更新save()
            $this->success('添加成功！', [], 1);
        }
        $this->error('添加失败！', [], 500);
    }
    /**
     *  我的反馈列表
     */
    public function detail()
    {
        $this->auth->id;
        $data = FeedbackModel::with('feedbackcate')
            ->field('feedback.id,feedback_cate_id,image,content')
            ->select();
        foreach ($data as &$v) {
            $v['feedback_cate_id'] = $v->feedbackcate->title;
            unset($v->feedbackcate);
            $v['image'] = strtolower(config("url_domain_root") . str_replace('\\', '/', $v['image']));
            $v['createtime'] = date('Y-m-d H:s', $v['createtime']);
        }
        $this->success('获取成功！', $data, 1);
    }
}
